/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */

package cn.hermit.scan;

import cn.hermit.spi.SPILoader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author JackGao 高建国
 * @description //TODO 设计说明
 * @date 2/6/2017
 */
public class ScanBoot {

    private static final Logger logger = Logger.getLogger(ScanBoot.class.getName());

    private static CountDownLatch latch = new CountDownLatch(1);

    public static void boot(String[] args) throws Exception {
        if (latch.getCount() == 0) {
            latch = new CountDownLatch(1);
        }

        List<ScanFilter> services = SPILoader.load(ScanFilter.class);
        Iterator<ScanFilter> filterIterator = services.iterator();
        List<ScanFilter> filterList = new ArrayList<>();
        filterList.add(new ResourcePatternFilter());
        logger.log(Level.INFO, "Added ScanFilter[{0}]", ResourcePatternFilter.class.getName());
        while (filterIterator.hasNext()) {
            ScanFilter filter = filterIterator.next();
            logger.log(Level.INFO, "Added ScanFilter[{0}]", filter.getClass().getName());
            filterList.add(filter);
        }

        ClasspathScanner scanner = ClasspathScanner.create().addFilter(filterList.toArray(new ScanFilter[]{}));
        scanner.scan();

        List<String> messages = scanner.getMessages();
        for (String message : messages) {
            logger.log(Level.INFO, "Scan Message: " + message);
        }

        logger.info("Scan System Booted!");

        latch.await();
    }

    public static void powerOff() {
        latch.countDown();
        logger.info("Scan System Power off!");
    }

    public static void main(String[] args) throws Exception {
        boot(args);
    }

}
